import React, {CSSProperties} from "react";

const customCache = new Set<string>();

interface IconFontProps {
    /**
     * iconfont图标名称
     */
    type: string;
    /**
     * 图标的样式名称
     */
    className?: string;
    /**
     * 自定义样式
     */
    style?: CSSProperties;
}

/**
 * @param scriptUrl symbol的脚本地址
 * @constructor
 */
const createFromIconfontCN = (scriptUrl: string) => {
    if (document && !customCache.has(scriptUrl)) {
        const script = document.createElement('script');
        script.setAttribute('src', scriptUrl);
        script.setAttribute('data-namespace', scriptUrl);
        customCache.add(scriptUrl);
        document.body.appendChild(script);
    }
    const Iconfont = React.forwardRef<HTMLSpanElement, IconFontProps>((props, ref: any) => {
        const {type, children, ...restProps} = props;

        let content: React.ReactNode = null;
        if (props.type) {
            content = <use xlinkHref={`#${type}`}/>;
        }

        return (
            <svg {...restProps} ref={ref}>
                {content}
            </svg>
        );
    });

    Iconfont.displayName = 'Iconfont';

    return Iconfont;
};

export default createFromIconfontCN;
